﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EWSEditor.CRM.Forms
{
    public partial class MailboxDetailsForm : Form
    {

        private SortableBindingList<MailboxAlert> _alertlist = new SortableBindingList<MailboxAlert>();
        public MailboxDetailsForm()
        {
            InitializeComponent();
            SetupForm();
           
        }

        private void SetupForm()
        {
            panelLoading.Visible = true;
            lblLoading.Visible = true;
            tabConfiguration.Enabled = false;
            btnOpenMailbox.Enabled = false;
            btnRefresh.Enabled = false;
            lblCurrentTime.Text = "Current GMT Time: ";
            Cursor = Cursors.WaitCursor;

            Thread RetrieveDataThread = new Thread(new ThreadStart(RetrieveMailbox));
            RetrieveDataThread.SetApartmentState(ApartmentState.STA);
            RetrieveDataThread.Start();

            Thread RetrieveAlertsThread = new Thread(new ThreadStart(RetrieveAlerts));
            RetrieveAlertsThread.SetApartmentState(ApartmentState.STA);
            RetrieveAlertsThread.Start();
        }

        private void RetrieveAlerts()
        {
            try
            {
                string fetchxml = GetFetch();
                FetchExpression fetchexpression = new FetchExpression(fetchxml);
                EntityCollection alerts = CrmAuthInfoFactory.GetOrgProxy().RetrieveMultiple(fetchexpression);
               
                this.Invoke(new Action(_alertlist.Clear));
                this.Invoke(new Action(grdAlerts.Rows.Clear));
                
                foreach (Entity alert in alerts.Entities)
                {
                    this.Invoke(new Action<MailboxAlert>(_alertlist.Add), new MailboxAlert(alert));
                }
                this.Invoke(new Action(SetAlertGrid));
            }
            catch (Exception ex)
            {
                this.Invoke(new Action<string, string>(FormUtility.ShowError),ex.StackTrace, "Exception Occurred While Retrieving Alerts");
            }
        }

        private void SetAlertGrid()
        {
           
            grdAlerts.DataSource = _alertlist;
        }

        private string GetFetch()
        {
            string regardingobjectid = CrmOrgMailboxCache.TargetMailbox.Id.ToString();
            string fetchxml =
                @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='10' page='1' returntotalrecordcount='true'>
    <entity name='tracelog'>
        <attribute name='tracelogid' />
        <attribute name='regardingobjectid' />
        <attribute name='parenttracelogid' />
        <attribute name='text' />
        <attribute name='level' />
        <attribute name='errordetails' />
        <attribute name='modifiedon' />
        <attribute name='createdby' />
        <attribute name='traceactionxml' />
        <attribute name='canbedeleted' />
        <attribute name='tracedetailxml' />
        <order attribute='modifiedon' descending='true' />
        <link-entity name='traceassociation' from='tracelogid' to='tracelogid'>
            <filter type='and'>
                <condition attribute='regardingobjecttypecode' operator='eq' value='9606' />
                <condition attribute='regardingobjectid' operator='eq' value='" + regardingobjectid + "'/>" +
            @"</filter>
        </link-entity>
        <filter type='and'>
            <condition attribute='collationlevel' operator='eq' value='0' />
        </filter>
    </entity>
</fetch>";

            return fetchxml;
        }

        private void RetrieveMailbox()
        {
            try
            {
                CrmOrgMailboxCache.RetrieveAndSetTargetMailbox(CrmAuthInfoFactory.GetOrgProxy());
            }
            catch (Exception ex)
            {
                this.Invoke(new Action<string, string>(FormUtility.ShowError), ex.StackTrace, "Exception Occurred While Refreshing Mailbox");
            }
            this.Invoke(new Action(SetFormProperties));
        }

        private void SetFormProperties()
        {
            try
            {
                FormUtility.BindAttributes(this.TopLevelControl, CrmOrgMailboxCache.TargetMailbox, "mailbox");
                panelLoading.Visible = false;
                lblLoading.Visible = false;
                tabConfiguration.Enabled = true;
                btnOpenMailbox.Enabled = true;
                btnRefresh.Enabled = true;
                lblCurrentTime.Text += DateTime.UtcNow.ToString(); 
                Cursor = Cursors.Default;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, "Error Loading Mailbox Details");
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void txtNoACTCount_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox9_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnOpenMailbox_Click(object sender, EventArgs e)
        {
            int idx = CrmAuthInfoFactory.CrmServiceUrl.ToLowerInvariant().IndexOf("/xrmservices");
            string baseurl = CrmAuthInfoFactory.CrmServiceUrl.Remove(idx);
            StringBuilder sbrecordurl = new StringBuilder(baseurl).Append("/main.aspx?etn=");
            sbrecordurl.Append("mailbox");
            sbrecordurl.Append("&pagetype=entityrecord&id=").Append(CrmOrgMailboxCache.TargetMailbox.Id.ToString());
            string recordurl = sbrecordurl.ToString();
            recordurl = Uri.EscapeUriString(recordurl);

            System.Diagnostics.Process.Start(recordurl);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            SetupForm();
        }
    }
}
